package com.changgou.order.consumer;


import com.alibaba.fastjson.JSON;
import com.changgou.order.dao.OrderMapper;
import com.changgou.order.pojo.Order;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
@RabbitListener(queues = "queue.order")
public class PayOrderUpdateListener {

    @Autowired
    private OrderMapper orderMapper;

    @RabbitHandler
    public void handler(String msg) {
        System.out.println(msg);
        Map<String, String> map = JSON.parseObject(msg, Map.class);
        if (map != null) {
            String out_trade_no = map.get("out_trade_no");
            if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
                Order order = orderMapper.selectByPrimaryKey(out_trade_no);
                // 设置订单状态为已支付
                order.setPayStatus("1");
                String time_end = map.get("time_end");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                try {
                    Date date = sdf.parse(time_end);
                    // 设置付款时间
                    order.setPayTime(date);
                    order.setUpdateTime(date);
                    order.setTransactionId(map.get("transaction_id"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                orderMapper.updateByPrimaryKeySelective(order);
            } else {
                Order order = orderMapper.selectByPrimaryKey(out_trade_no);
                order.setIsDelete("1"); // 直接将订单设置为删除状态
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }
    }
}
